from PySide6.QtWidgets import QWidget, QPushButton
from PySide6.QtCore import Qt, QObject
from QtControls.my_widget import MyWidget  # 导入子窗口类
from QtControls.my_area import My_Area
import Global

class MainWindow(QWidget):
    """主窗口类"""
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        """初始化主窗口UI"""
        self.setWindowTitle("主窗口")
        self.resize(300, 200)

        # 打开子窗口的按钮
        self.btn_open_child = QPushButton("打开子窗口", self)
        self.btn_open_child.setGeometry(100, 80, 100, 40)
        self.btn_open_child.clicked.connect(self.open_child_window)



    def open_child_window(self):
        """打开子窗口（复用已有或新建）"""
        child_class = My_Area
        child_window = self.__find_child_window_by_class(child_class)

        if not child_window:
            child_window = child_class(self)  # 指定主窗口为父对象
            child_window.setWindowFlags(Qt.Window)
            child_window.setAttribute(Qt.WA_DeleteOnClose, False)
            print(f"【主窗口】新建{child_class.__name__}子窗口")

        self.hide()
        child_window.show()
        child_window.raise_()
        



    # 下方为私有方法
    def __find_child_window_by_class(self, target_class):
        """根据类类型查找直接子窗口"""
        # 正确参数顺序：目标类型、名称筛选（空字符串表示不筛选）、查找选项
        direct_children = self.findChildren(QObject, "", Qt.FindDirectChildrenOnly)
        for child in direct_children:
            if isinstance(child, target_class):
                return child
        print(f"【主窗口】未找到{target_class.__name__}类型的子窗口")
        return None